/*
 @description: 管理员登录
*/
'use strict';
const Controller = require('egg').Controller;
const utility = require("utility")
class AdminTokenController extends Controller {
    async index() {
        const {
            ctx,
            app
        } = this;
        const {
            username,
            password
        } = ctx.request.body;
        if (username && password) {
            const power = await app.mysql.query(`select jurisdiction from adminuser where name like '${username}'`);
            const quanxian = power[0].jurisdiction;
            const user = await app.mysql.query(`select name from adminuser`);
            const result = user.find(item => item.name === username);
            if (result) {
                let pwd = await app.mysql.query(`select password,headPortrait from adminuser 
                where name='${result.name}'`);
                // let touxiang = await app.mysql.query(``)
                // console.log(pwd[0].password, utility.md5(password));

                if (pwd[0].password === utility.md5(password)) {
                    const iner = {
                        username,
                        log_time: Date.now(),
                        end_time: Date.now() + 3600 * 2
                    };
                    const time1 = new Date();//直接用 new Date(时间戳) 格式转化获得当前时间
                    const time = time1.toLocaleDateString().replace(/\//g, "-") + " " + time1.toTimeString().substr(0, 8);//再利用拼接正则等手段转化为yyyy-MM-dd hh:mm:ss 格式
                    // 不过这样转换在某些浏览器上会出现不理想的效果，因为toLocaleDateString()方法是因浏览器而异的，比如 IE为2016年8月24日 22:26:19 格式 搜狗为Wednesday, August 24, 2016 22:39:42
                    const token = app.jwt.sign(iner, app.config.jwt.sercet);
                    console.log(token);
                    // const row = {
                    //     pwd,time,quanxian
                    // }
                    ctx.body = {
                        code: 0,
                        msg: "登录成功",
                        token,pwd,time,quanxian
                        // row
                    }

                } else {
                    ctx.body = {
                        code: 4004,
                        msg: '账号或密码错误'
                    }

                }
            } else {
                ctx.body = {
                    code: 4001,
                    msg: '管理员不存在'
                }
            }
        }
    }
}
module.exports = AdminTokenController;